Why Use the Repository Pattern in a Laravel Application

Why Use the Repository Pattern in a Laravel Application

The Repository pattern.

Repositories are classes or components that encapsulate the logic required to access data sources.


They centralize common data access functionality, providing better maintainability and decoupling the infrastructure or technology used to access databases from the domain model layer.


The basic difference between model and Repository are

Models allow you to query for data in your tables, as well as insert new records into the table. What this is saying, is a Model opens access to a database table. It also allows you to relate to other models to pull out data without having to write individual queries.

A repository allows you to handle a Model without having to write massive queries inside of a controller. In turn, keeping the code tidier, modular and easier to debug should any errors arise.


Example 

You could use a repository in the following way:

public function makeNotification($class, $title, $message)
{
    $notification = new Notifications;
    ...
    $notification->save();
    return $notification->id;
}
public function notifyAdmin($class, $title, $message)
{
    $notification_id = $this->makeNotification($class, $title, $message);
    $users_roles = RolesToUsers::where('role_id', 1)->orWhere('role_id', 2)->get();
    $ids = $users_roles->pluck('user_id')->all();
    $ids = array_unique($ids);
    foreach($ids as $id) {
        UserNotifications::create([
            'user_id' => $id,
            'notification_id' => $notification_id,
            'read_status' => 0
        ]);
    }
}

 controller:

protected $notification;
public function __construct(NotificationRepository $notification)
{
    $this->notification = $notification;
}
public function doAction()
{
    ...
    $this->notification->notifyAdmin('success', 'User Added', 'A new user joined the system');
    ...
}


The repository pattern consists of adding an abstraction layer between the data access layer and the business logic layer of an application that are in charge of accessing the data source and obtaining the different data models. It is a data access pattern that prompts a more loosely coupled approach to data access



Tags

We are Recommending you:

Leave a comment

Comments